import {
  commands,
  window,
  workspace,
  Range,
  Position,
  WorkspaceEdit,
} from "vscode";

function insertText(text: string) {
  const editor = window.activeTextEditor;
  const selection = editor?.selection;
  // 获取光标当前行
  const lineOfSelectedVar: number = selection?.active.line || 0;

  // edit方法获取editBuilder实例，在后一行添加
  editor?.edit((editBuilder) => {
    editBuilder.insert(new Position(lineOfSelectedVar + 1, 0), text);
    commands.executeCommand("editor.action.formatDocument");
  });
}

/**
 * registerCommand完整的 API 是：
 * 	 registerCommand(command: string, callback: (args: any[]) => any, thisArg?: any): Disposable
 *   主要功能是给功能代码(callback)注册一个命令(command)，
 *   然后通过 subscriptions.push() 给插件订阅对应的 command 事件。
 */
export const insertLog = commands.registerCommand(
  "vs-zjplugin.insertLog",
  () => {
    //拿到当前编辑页面的内容对象
    const editor = window.activeTextEditor;
    // 拿到光标选中的文本并格式化
    const selection = editor?.selection;
    let text = editor?.document.getText(selection) || "";
    text = text.replace(/\‘|\“|\”|\’/gi, "");
    //这里拼出console语句
    let logToInsert = `\n\n`;
    if (/err|error/.test(text)) {
      logToInsert = `\n\n`;
    } else if (/\[.*\]/.test(text)) {
      logToInsert = `\nconsole.table(${text});\n`;
    }

    text ? insertText(logToInsert) : insertText("");
  }
);

//添加 time console
function addTimeLog() {
  const editor = window.activeTextEditor;
  const selection = editor?.selection;
  // 获取光标当前行
  const lineOfSelectedVar: number = selection?.active.line || 0;
  const lineEnd: number = selection?.end.line || 0;
  const startTime = `\n`;
  const endTime = `\n`;
  // edit方法获取editBuilder实例，在后一行添加
  editor?.edit((editBuilder) => {
    // editBuilder.insert(new Position(lineOfSelectedVar, 0),"\n")
    editBuilder.insert(new Position(lineOfSelectedVar, 0), startTime);
    editBuilder.insert(new Position(lineEnd + 1, 0), "\n");
    editBuilder.insert(new Position(lineEnd + 1, 0), endTime);
  });
}

//插入console.time
export const timeLog = commands.registerCommand("vs-zjplugin.timeLog", () => {
  //拿到当前编辑页面的内容对象
  const editor = window.activeTextEditor;
  // 拿到光标选中的文本并格式化
  const selection = editor?.selection;
  const text = editor?.document.getText(selection) || "";

  text ? addTimeLog() : void 0;
});

function getAllLogStatements() {
  const editor = window.activeTextEditor;
  // 获取编辑器页面文本
  const document = editor!.document;
  const documentText = document?.getText() || "";
  let logStatements = [];
  // 检测console的正则表达式
  const logRegex = /console.(log|debug|info|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*)\);?/g;
  let match;
  // 正则循环匹配页面文本
  while ((match = logRegex.exec(documentText))) {
    // 每次匹配到当前的范围--Range
    let matchRange = new Range(
      document.positionAt(match.index),
      document.positionAt(match.index + match[0].length)
    );
    if (!matchRange.isEmpty)
      // 把Range放入数组
      logStatements.push(matchRange);
  }
  return logStatements;
}
//清楚console.xxx
export const clearLog = commands.registerCommand("vs-zjplugin.clearLog", () => {
  const editor = window.activeTextEditor;
  if (!editor) {
    return;
  }

  let workspaceEdit = new WorkspaceEdit();
  const document = editor.document;

  const logStatements = getAllLogStatements();

  // 循环遍历每个匹配项的range，并删除
  logStatements.forEach((log) => {
    workspaceEdit.delete(document.uri, log);
  });
  // 完成后显示消息提醒
  workspace.applyEdit(workspaceEdit).then(() => {
    window.showInformationMessage(
      `${logStatements.length} console.log deleted`
    );
    commands.executeCommand("editor.action.formatDocument");
  });
});
